package com.atguigu.edusocket.service.impl;

import cn.hutool.core.util.RandomUtil;
import com.atguigu.edusocket.config.MinioConfig;
import com.atguigu.edusocket.config.WebSocketServer;
import com.atguigu.edusocket.entity.AlarmNotification;
import com.atguigu.edusocket.entity.EventQuery;
import com.atguigu.edusocket.mapper.AlarmNotificationMapper;
import com.atguigu.edusocket.service.AlarmNotificationService;
import com.atguigu.edusocket.utils.MinioClientUtils;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.minio.errors.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.io.FileInputStream;
import java.io.IOException;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;

/**
 * <p>
 * 报警数据推送 服务实现类
 * </p>
 *
 * @author ryan
 * @since 2021-11-26
 */
@Service
public class AlarmNotificationServiceImpl extends ServiceImpl<AlarmNotificationMapper, AlarmNotification> implements AlarmNotificationService {

    @Autowired
    private MinioClientUtils minioClientUtils;

    @Autowired
    private MinioConfig minioConfig;

    @Override
    public void pageQuery(EventQuery eventQuery, Page<AlarmNotification> coursePage) {
        String status = eventQuery.getStatus();
        String title = eventQuery.getCameraId();
        QueryWrapper<AlarmNotification> wrapper = new QueryWrapper<>();
        if(!StringUtils.isEmpty(status)){
            wrapper.eq("status", status);
        }
        if(!StringUtils.isEmpty(title)){
            wrapper.eq("camera_id", title);
        }
        wrapper.orderByDesc("gmt_create");
        baseMapper.selectPage(coursePage, wrapper);
    }

    @Override
    public String saveAndNotify(AlarmNotification alarmNotification) throws IOException, ServerException, InvalidBucketNameException, InsufficientDataException, ErrorResponseException, NoSuchAlgorithmException, InvalidKeyException, InvalidResponseException, XmlParserException, InternalException {
        String sourcePath = alarmNotification.getSourcePath();
        FileInputStream fileInputStream = new FileInputStream(sourcePath);
        String randomName = RandomUtil.randomString(6) + "_" + sourcePath.substring(sourcePath.lastIndexOf('/') + 1);
        String objectName = "profiles/" + randomName;
        String url = minioClientUtils.uploadImage(minioConfig.getBucketName(), objectName, fileInputStream);
        alarmNotification.setSourcePath(url);
        baseMapper.insert(alarmNotification);
        String message = "new alarm";
        String toUserId = "1";
        WebSocketServer.alarmNotify(message, toUserId);
        return sourcePath;
    }
}
